
package cc.jinglupeng.kom.pool;

import cc.jinglupeng.kom.util.EmptyWatch;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

public class ZookeeperFactory implements PoolableObjectFactory<ZooKeeper> {

    private Logger logger = LoggerFactory.getLogger(ZookeeperFactory.class);

    private String[] connectStrings;
    private int timeout = 3000;
    private Watcher watcher;
    private boolean canBeReadOnly = true;
    private AtomicInteger counter = new AtomicInteger(0);

    public ZookeeperFactory(String[] connectStrings, int timeout) {
        logger.info("connectStrings {}", connectStrings);
        logger.info("timeout {}", timeout);

        this.connectStrings = connectStrings;
        this.timeout = timeout;
    }

    public String[] getConnectStrings() {
        return connectStrings;
    }

    public void setConnectStrings(String[] connectStrings) {
        this.connectStrings = connectStrings;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public Watcher getWatcher() {
        return watcher;
    }

    public void setWatcher(Watcher watcher) {
        this.watcher = watcher;
    }

    public boolean isCanBeReadOnly() {
        return canBeReadOnly;
    }

    public void setCanBeReadOnly(boolean canBeReadOnly) {
        this.canBeReadOnly = canBeReadOnly;
    }

    @Override
    public ZooKeeper makeObject() throws Exception {
        if (connectStrings == null || connectStrings.length == 0) {
            throw new Exception("cannot find zookeeper config.");
        }
        int index = counter.getAndAdd(1) % connectStrings.length;
        return new ZooKeeper(connectStrings[index], getTimeout(), EmptyWatch.getInstance());
    }

    @Override
    public void destroyObject(ZooKeeper zooKeeper) throws Exception {
        if (zooKeeper != null) {
            zooKeeper.close();
        }
    }

    @Override
    public boolean validateObject(ZooKeeper zooKeeper) {
        return zooKeeper.getState().isAlive();
    }

    @Override
    public void activateObject(ZooKeeper zooKeeper) throws Exception {
    }

    @Override
    public void passivateObject(ZooKeeper zooKeeper) throws Exception {

    }
}
